/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.controller;

import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.vos.AuthorizationVo;
import cn.easyplatform.messages.vos.EnvVo;
import cn.easyplatform.messages.vos.LoginVo;
import cn.easyplatform.messages.vos.OrgVo;
import cn.easyplatform.spi.service.IdentityService;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.web.contexts.Contexts;
import cn.easyplatform.web.service.ServiceLocator;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.Window;

import java.util.ArrayList;
import java.util.List;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SelectOrgController extends SelectorComposer<Window> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Wire("listbox")
    private Listbox listbox;

    private LoginVo userInfo;

    @Override
    public void doAfterCompose(Window comp) throws Exception {
        super.doAfterCompose(comp);
        listbox.setSelectedIndex(0);
        userInfo = (LoginVo) Executions.getCurrent().getArg().get("vo");
    }

    @Listen("onClick=#ok;onOK=window")
    public void submit() {
        if (listbox.getSelectedItem() == null)
            listbox.setSelectedIndex(0);
        OrgVo org = listbox.getSelectedItem().getValue();
        IdentityService uc = ServiceLocator
                .lookup(IdentityService.class);
        SimpleRequestMessage req = new SimpleRequestMessage(org.getId());
        IResponseMessage<?> resp = uc.selectOrg(req);
        if (resp.isSuccess()) {
            Session session = listbox.getDesktop().getSession();
            EnvVo env = Contexts.getEnv();
            userInfo.setOrgId(org.getId());
            AuthorizationVo av = (AuthorizationVo) resp.getBody();
            env.setMainPage(av.getMainPage());
            List<OrgVo> orgs = new ArrayList<OrgVo>(listbox.getItems().size());
            for (Listitem item : listbox.getItems()) {
                OrgVo ov = item.getValue();
                orgs.add(ov);
            }
            session.setAttribute(Contexts.PLATFORM_USER, userInfo);
            session.setAttribute(Contexts.PLATFORM_USER_AUTHORIZATION,
                    resp.getBody());
            session.setAttribute(Contexts.PLATFORM_APP_ENV, env);
            session.setAttribute(Contexts.PLATFORM_USER_ORGS, orgs);
            Executions.sendRedirect("/main.go");
        }
    }

    @Listen("onClick=#cancel;onCancel=window")
    public void cancel() {
        IdentityService uc = ServiceLocator
                .lookup(IdentityService.class);
        uc.logout(new SimpleRequestMessage());
        Sessions.getCurrent().removeAttribute(Constants.SESSION_ID);
        IResponseMessage<?> resp = uc.getAppEnv(new SimpleRequestMessage(Contexts.getEnv()));
        if (resp.isSuccess()) {
            EnvVo env = (EnvVo) resp.getBody();
            Sessions.getCurrent().setAttribute(Constants.SESSION_ID, env.getSessionId());
        }
        this.getSelf().detach();
    }
}
